<template>
  <view class="userPage">
    <!-- 背景图片 -->
    <image class="bg-image" :src="bgImage" mode="widthFix"></image>
    <!-- 导航栏 -->
    <s-nav-bar title="个人中心" background="transparent" :titleStyle="{ color: '#fff', fontWeight: 'bold' }" back
      :backStyle="{ color: '#fff' }">
      <view slot="right" @click="showUpdate">
        <s-icon name="service" color="#fff" size="20"></s-icon>
      </view>
    </s-nav-bar>

    <!-- 主内容区域 -->
    <scroll-view class="main-scroll" scroll-y="true">
      <view class="main">
        <view class="top">
          <view class="left">
            <!-- 顶部用户信息区域 -->
            <view class="info">
              <!-- 左侧头像 -->
              <view class="avatar" @click="chooseAvatar">
                <view class="imgBox" v-if="avatarUrl">
                  <image :src="avatarUrl" mode="aspectFill" class="avatarImg"></image>
                </view>
                <view v-else class="defaultAvatar">
                  <view class="nameTxt">{{
                    userInfo.real_name ? userInfo.real_name.slice(0, 1) : ""
                  }}</view>
                </view>
                <view class="uploadTip">点击更换头像</view>
              </view>

              <!-- 右侧用户信息 -->
              <view class="info-right">
                <view class="name">{{ userInfo.real_name }}</view>
                <view class="company">{{ userInfo.company }}</view>
              </view>
            </view>
          </view>
          <view class="right">
            <view class="button" @click="showUpdate">
              <s-icon name="setting-o" color=" var(--v-theme)" size="12"></s-icon>
              <view class="text">修改资料</view>
            </view>
          </view>
        </view>
        <view class="month-stats">
          <view class="month-name">
            {{ currentMonth }}
          </view>
          <view class="list">
            <view class="item">
              <view class="value">
                <view class="text">{{ summary.count }}</view>
                <view class="unit">单</view>
              </view>
              <view class="label">月度单量</view>
            </view>
            <view class="item">
              <view class="value">
                <view class="text">{{ summary.total_deposit }}</view>
                <view class="unit">元</view>
              </view>
              <view class="label">收款金额</view>
            </view>
            <view class="item">
              <view class="value">
                <view class="text">{{ summary.total_final_payment }}</view>
                <view class="unit">元</view>
              </view>
              <view class="label">待收金额</view>
            </view>
          </view>
        </view>
        <!-- 第一行菜单 -->
        <!-- <view class="menuBox row">
          <view class="box">
            <s-icon
              name="manager"
              size="22"
              class="icon"
            />
            <view class="account">{{ userInfo.username }}</view>
          </view>
          <view
            class="box"
            @click="swiTo('pages/order/list')"
          >
            <s-icon
              name="todo-list-o"
              size="22"
              class="icon"
            />
            <view class="account">我的订单</view>
          </view>
          <view
            class="box"
            @click="openChange"
          >
            <s-icon
              name="lock"
              size="22"
              class="icon"
            />
            <view class="account">修改密码</view>
          </view>
        </view> -->

        <!-- 第二行菜单 -->
        <view class="menuBox">
          <div class="box column">
            <view class="vip">
              <view class="left">
                <view class="icon">
                  <image class="vipLogo" src="http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/vip.svg"
                    mode="widthFix" />
                </view>
                <view class="info">个人版，有效期至{{ youxiaoqi }}</view>
              </view>
              <view class="right">
                <view class="button">会员详情</view>
              </view>
            </view>
            <view class="title">
              <view class="text"> 我的设置 </view>
            </view>
            <view class="settingList">
              <!-- <view class="item" @click="navTo('pages/member/index')"> -->

              <view class="item" @click="navTo('/pages/extra/category/index')">
                <view class="iconBox">
                  <s-icon name="http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/icons/fwlx.png" class="icon" />
                </view>
                <view class="label"> 服务类型 </view>
              </view>
              <view class="item" @click="navTo('/pages/extra/source/index')">
                <view class="iconBox">
                  <s-icon name="http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/icons/ddqd.png" class="icon" />
                </view>
                <view class="label"> 订单渠道 </view>
              </view>
              <view class="item" @click="navTo('/pages/extra/payMethod/index')">
                <view class="iconBox">
                  <s-icon name="http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/icons/zffs.png" class="icon" />
                </view>
                <view class="label"> 支付方式 </view>
              </view>
              <view class="seprate"></view>
              <view class="item" @click="navTo('/pages/extra/member/index')">
                <view class="iconBox">
                  <s-icon name="http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/icons/yglb.png" class="icon" />
                </view>
                <view class="label"> 员工列表 </view>
              </view>
            </view>
          </div>
        </view>

        <!-- 第三行菜单 -->
        <view class="menuBox">
          <div class="box">
            <view class="title">
              <view class="text"> 常用工具 </view>
            </view>
            <view class="menuList">
              <view class="item">
                <view class="iconBox">
                  <image class="tu" src="https://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/iconsmine/dels.png" />
                  <!-- <s-icon name="share" /> -->
                </view>
                <view class="label"> 数据导出 </view>
                <s-icon name="arrow" color="#aaa" />
              </view>
              <view class="item">
                <view class="iconBox">
                  <image class="tu" src="https://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/iconsmine/dels.png" />

                </view>
                <view class="label"> 回收站 </view>
                <s-icon name="arrow" color="#aaa" />
              </view>
              <view class="item">
                <view class="iconBox">
                  <image class="tu" src="https://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/iconsmine/dels.png" />

                </view>
                <view class="label"> 系统教程 </view>
                <s-icon name="arrow" color="#aaa" />
              </view>
              <view class="item" @click="openChange">
                <view class="iconBox">
                  <image class="tu" src="https://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/iconsmine/dels.png" />

                </view>
                <view class="label"> 修改密码 </view>
                <s-icon name="arrow" color="#aaa" />
              </view>
              <view class="item" @click="logOut">
                <view class="iconBox">
                  <image class="tu" src="https://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/iconsmine/dels.png" />

                </view>
                <view class="label"> 退出 </view>
                <s-icon name="arrow" color="#aaa" />
              </view>
            </view>
          </div>
        </view>
      </view>
    </scroll-view>
    <v-change v-model="showChangePassword" />
    <v-update v-model="showUpdateUserInfo" :user-data="userInfo" @update-success="handleUpdateSuccess" />
    <!-- 底部导航 -->
    <v-tabbar @tabBarChange="tabBarChange" :tabIndex="4" />
  </view>
</template>

<script>
import formatDate from "uni_modules/s-ui/utils/formatDate.js";
import sNavBar from '@/uni_modules/s-ui/components/s-nav-bar/s-nav-bar.vue';
import sIcon from '@/uni_modules/s-ui/components/s-icon/s-icon.vue';
export default {
  data() {
    return {
      showUpdateUserInfo: false,
      userInfo: {},
      showChangePassword: false,
      currentMonth: "",
      youxiaoqi: "",
      filterMonth: "",
      summary: {},
      bgImage: "http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/user-bg.jpg", // 默认背景图片
      avatarUrl: "" // 用户头像URL
    };
  },
  computed: {
    bgStyle() {
      return {
        'background-image': `url(${this.bgImage})`
      };
    }
  },
  components: {
    sNavBar,
    sIcon
  },
  onLoad() {
    this.getUserInfo();
    this.getCurrentMonth();
    this.getBackgroundImage();
  },
  onShow() { },
  onHide() { },
  methods: {
    getCurrentMonth() {
      const now = Date.now();
      this.currentMonth = formatDate(now, "YYYY年M月");
      this.filterMonth = formatDate(now, "YYYY-MM");
      this.youxiaoqi = formatDate(now + 1000 * 3600 * 24 * 30, "YYYY年MM月DD");
    },
    navTo(url) {
      uni.navigateTo({ url: url });
    },
    swiTo(url) {
      uni.switchTab({
        url: url,
      });
    },
    tabBarChange(url) {
      uni.switchTab({
        url: url,
      });
    },
    getUserInfo() {
      this.sjuAjax.get("/user/info", {}, (res) => {
        if (res && res.code == 200) {
          this.userInfo = res.data;
          // 如果用户信息中有头像URL，则设置头像
          if (res.data.avatar) {
            this.avatarUrl = res.data.avatar;
          }
        }
      });
      this.sjuAjax.get(
        "/order/statsByMonth",
        {
          month: this.filterMonth,
        },
        (res) => {
          if (res.code === 200) {
            console.log(res.data);
            this.summary = res.data.stats || {};
            this.summary.count = res.data?.orders.length || 0;
          }
        }
      );
    },
    getBackgroundImage() {
      // 调用 getAll 接口获取背景图片数据
      this.sjuAjax.get("/setting/getAll", {}, (res) => {
        if (res && res.code == 200 && res.data && res.data.profile && res.data.profile.length > 0) {
          // 使用 res.data.profile[0] 的图片
          this.bgImage = res.data.profile[0].url || "http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/user-bg.jpg";
        }
      });
    },
    chooseAvatar() {
      // 选择图片
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.uploadAvatar(tempFilePath);
        },
        fail: () => {
          this.sjuAlert.showInfo('选择图片失败');
        }
      });
    },
    uploadAvatar(filePath) {
      // 使用新的sjuAjax.upload方法上传头像
      this.sjuAjax.upload('/user/uploadAvatar', {}
        , filePath
        , 'file'
        , true
      ).then(res => {
        if (res && res.code === 200) {
          // 上传成功，更新头像URL
          this.avatarUrl = res.data.url;
          // 更新用户信息中的头像
          this.userInfo.avatar = res.data.url;
          this.sjuAlert.showInfo('上传成功');
          // 可以选择重新获取用户信息以同步更新
          this.getUserInfo();
        }
      }).catch(err => {
        console.error('头像上传失败:', err);
      });
    },
    openChange() {
      this.showChangePassword = true;
    },
    showUpdate() {
      this.showUpdateUserInfo = true;
    },
    handleUpdateSuccess(updatedData) {
      // 更新本地用户信息
      this.userInfo = {
        ...this.userInfo,
        ...updatedData,
      };
      // 如果更新了头像，同步更新
      if (updatedData.avatar) {
        this.avatarUrl = updatedData.avatar;
      }
    },
    logOut() {
      this.sjuAlert.showConfirm(
        "确定退出吗？",
        () => {
          uni.removeStorageSync("token");
          uni.removeStorageSync("token_expire");
          this.sjuNav.navigateTo("/user/login");
        },
        () => { }
      );
    },
  },
};
</script>
<style lang="scss">
.tu {
  width: 100%;
  height: 100%;
}

.userPage {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;

  .bg-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: -1;
  }

  .title {
    font-size: 28rpx;
    font-weight: bold;
    padding: 24rpx;

    .text {
      line-height: 1em;
      padding-left: 24rpx;
      border-left: var(--v-theme) 8rpx solid;
    }
  }
}

.main-scroll {
  height: 0;
  flex-grow: 1;
}

/* 顶部区域 */
.top {
  display: flex;
  align-items: center;
  box-sizing: border-box;
  justify-content: space-between;
  padding: 0 10rpx;

  .info {
    display: flex;
    align-items: center;

    .avatar {
      margin-right: 30rpx;
      /* Replaced gap: 30rpx */
    }

    /* 左侧头像 */
    .avatar {
      width: 90rpx;
      height: 90rpx;
      border-radius: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-shrink: 0;
      position: relative;
      cursor: pointer;

      .imgBox {
        width: 100%;
        height: 100%;
        border-radius: 60rpx;
        overflow: hidden;
        background: var(--v-third);
        border: #fff 4rpx solid;
        box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);

        .avatarImg {
          width: 90rpx;
          height: 90rpx;
          border-radius: 60rpx;
        }
      }

      .defaultAvatar {
        width: 100%;
        height: 100%;
        background: var(--v-third);
        color: #fff;
        border: #fff 4rpx solid;
        border-radius: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 40rpx;
        text-shadow: 4rpx 4rpx 8rpx rgba(0, 0, 0, 0.4);
        box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);

        .nameTxt {
          line-height: 1;
        }
      }

      .uploadTip {
        position: absolute;
        bottom: -30rpx;
        left: 50%;
        transform: translateX(-50%);
        font-size: 20rpx;
        color: var(--v-third);
        white-space: nowrap;
      }
    }

    /* 右侧用户信息 */
    .info-right {
      display: flex;
      flex-direction: column;
      color: var(--v-third);

      .name {
        margin-bottom: 10rpx;
        /* Replaced gap: 10rpx */
        font-size: 44rpx;
        letter-spacing: 4rpx;
        line-height: 1.2;
      }

      .company {
        font-size: 28rpx;
      }
    }
  }

  .right {
    .button {
      background: rgba(255, 255, 255, 0.8);
      backdrop-filter: blur(2px);
      color: var(--v-theme);
      border: var(--v-theme) 1px solid;
      font-size: 24rpx;
      font-weight: bold;
      padding: 10rpx 20rpx;
      border-radius: 10rpx;
      display: flex;
      align-items: center;

      >* {
        margin-right: 10rpx;

        /* Replaced gap: 10rpx */
        &:last-child {
          margin-right: 0;
          /* Remove margin from last child */
        }
      }
    }
  }
}

/* 主内容区域 */
.main {
  padding: 0 30rpx;
  display: flex;
  flex-direction: column;
  padding-top: 60rpx;

  >* {
    margin-bottom: 40rpx;

    /* Replaced gap: 40rpx */
    &:last-child {
      margin-bottom: 0;
      /* Remove margin from last child */
    }
  }

  .menuBox {
    display: flex;
    flex-direction: column;

    >* {
      margin-bottom: 40rpx;

      /* Replaced gap: 40rpx */
      &:last-child {
        margin-bottom: 0;
        /* Remove margin from last child */
      }
    }

    /* 横向排列的菜单 */
    &.row {
      justify-content: space-between;
      flex-direction: row;

      .box {
        align-items: center;
        flex-direction: column;
        padding: 0;
        background: rgba(255, 255, 255, 0.47);
        background: linear-gradient(to bottom,
            rgba(255, 255, 255, 0),
            rgba(255, 255, 255, 0.67));

        .icon {
          background: #ffffff;
          width: 80rpx;
          height: 80rpx;
          border-radius: 10rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #47c5c4;
          margin-bottom: 20rpx;
        }

        &:nth-child(2) {
          .icon {
            color: var(--v-theme);
          }
        }

        .account {
          font-size: 28rpx;
          color: #666;
        }
      }
    }

    .settingList {
      display: flex;
      padding: 28rpx;

      >* {
        margin-right: 28rpx;

        /* Replaced gap: 28rpx */
        &:last-child {
          margin-right: 0;
          /* Remove margin from last child */
        }
      }

      .item {
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        align-items: center;

        .iconBox {
          margin-bottom: 10rpx;
          /* Replaced gap: 10rpx */
          color: #4c4e5f;
        }

        .iconBox {
          font-size: 80rpx;
        }

        .label {
          color: #414141;
        }
      }
    }

    /* 菜单盒子 */
    .box {
      background: rgba(255, 255, 255, 0.97);
      border-radius: 20rpx;
      box-shadow: var(--v-shadow);
      display: flex;
      flex-direction: column;

      >* {
        margin-bottom: 10rpx;

        /* Replaced gap: 10rpx */
        &:last-child {
          margin-bottom: 0;
          /* Remove margin from last child */
        }
      }

      padding: 20rpx 0;

      &.column {
        flex-direction: column;
        padding-top: 0;
        overflow: hidden;
      }

      /* 菜单列表 */
      .menuList {
        width: 100%;

        .item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 30rpx;

          .label {
            margin-right: 20rpx;
            /* Replaced gap: 20rpx */
          }

          .label {
            flex-grow: 1;
            font-size: 30rpx;
            color: #333;
          }

          .iconBox {
            width: 55rpx;
            height: 55rpx;
            // background: var(--v-theme);
            color: #fff;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 26rpx;
            margin-right: 20rpx;
          }
        }
      }
    }
  }
}

.vip {
  height: 128rpx;
  width: 100%;
  background: url("http://ziyuanstatic.oss-cn-beijing.aliyuncs.com/static/vip-bg.png");
  background-size: 100% 100%;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    transform: translateY(-8rpx);

    .icon {
      .vipLogo {
        width: 128rpx;
      }
    }

    .info {
      color: #c8b276;
      text-indent: 24rpx;
      margin-top: -14rpx;
      font-size: 24rpx;
    }
  }

  .right {
    padding-right: 20rpx;

    .button {
      background: #c8b276;
      color: #333541;
      padding: 8rpx 22rpx;
      font-size: 24rpx;
      border-radius: 10rpx;
      font-weight: bold;
    }
  }
}

.month-stats {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
  border-radius: 20rpx;
  margin-top: 44rpx;
  padding: 20rpx;
  box-shadow: var(--v-shadow);

  .month-name {
    padding: 28rpx;
    padding-top: 0;
    text-align: center;
    font-weight: bold;
  }

  .list {
    display: flex;

    >* {
      margin-right: 28rpx;

      /* Replaced gap: 28rpx */
      &:last-child {
        margin-right: 0;
        /* Remove margin from last child */
      }
    }

    .item {
      flex-grow: 1;

      .value {
        display: flex;
        align-items: baseline;
        justify-content: center;

        .text {
          margin-right: 8rpx;
          /* Replaced gap: 8rpx */
          color: var(--v-theme);
          font-size: 50rpx;
        }
      }

      .label {
        text-align: center;
        color: var(--v-gray);
      }
    }
  }
}

.seprate {
  width: 1px;
  height: 100rpx;
  background: linear-gradient(to bottom,
      transparent,
      rgba(81, 76, 127, 0.75),
      transparent);
}
</style>